var flagPast = 0,
	flagWarning = 0,
	flagShare = 0;

var markerShare = null,
	markerLocation = null;

var problemMarkerLayer = {},
	locationMarkerLayer = {},
	trafficLayer = {},
	warningLayer ={},
	boundDistrictLayer = {};

var daytimePast = [(new Date).getDate(), (new Date).getMonth()+1, (new Date).getFullYear(), 5, 0];

var LeafIcon = L.Icon.extend({
	options: {
		iconSize:     [32, 32],
		iconAnchor:   [16, 32],
		popupAnchor:  [-6, -25]
	}
});

var accident = new LeafIcon({iconUrl: 'images/accident32.png'}),
	construction = new LeafIcon({iconUrl: 'images/construction32.png'}),
	broken_light = new LeafIcon({iconUrl: 'images/broken_light32.png'}),
	flood = new LeafIcon({iconUrl: 'images/flood32.png'}),
	police = new LeafIcon({iconUrl: 'images/police32.png'}),
	warning = new LeafIcon({iconUrl: 'images/warning32.png'}),
	repair_car = new LeafIcon({iconUrl: 'images/repair_car32.png'}),
	gas_station = new LeafIcon({iconUrl: 'images/gas_station32.png'}),
	store = new LeafIcon({iconUrl: 'images/store32.png'}),
	coffee = new LeafIcon({iconUrl: 'images/coffee32.png'}),
	parking_lot = new LeafIcon({iconUrl: 'images/parking_lot32.png'}),
	hospital = new LeafIcon({iconUrl: 'images/hospital32.png'}),
	geolocationIcon = L.icon({
		iconUrl: 'images/bluedot.png',
		iconSize:     [20, 20]
	}),
	pushPin = L.icon({
	    iconUrl: 'images/pushpin.png',
	    iconSize:     [48, 48],
	    iconAnchor:   [24, 48],
	    popupAnchor:  [1, -40]
	});


url_satellite
var	url_satellite='http://{s}.tiles.mapbox.com/v3/dennisl.map-6g3jtnzm/{z}/{x}/{y}.png',
	url_mapQuest = 'http://otile3.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.jpg',
	url_OSMtransport = 'http://{s}.tile2.opencyclemap.org/transport/{z}/{x}/{y}.png',
	url_OSMstandart = 'http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png',

	transport = new L.TileLayer(url_OSMtransport, {minZoom: 12, maxZoom: 18,
		attribution: ''}),
	standart = new L.TileLayer(url_OSMstandart, {minZoom: 12, maxZoom: 18,
		attribution: ''}),
	satellite = new L.TileLayer(url_satellite, {minZoom: 12, maxZoom: 18,
		attribution: ''}),
	mapQuest = new L.TileLayer(url_mapQuest, {minZoom: 12, maxZoom: 18,
		attribution: ''}),
	mapQuest2 = new L.TileLayer(url_mapQuest, {minZoom: 9, maxZoom:15});

var baseMaps = {
	'OSM Transport':transport,
	'MapQuestdsfsd':mapQuest,
	'OSM Standart':standart,
	'Mapbox Satellite': satellite
};
			
var map = new L.Map('MainMap', {
	    layers: [transport],
	    center: [10.772113,106.657832],
	    zoom: 16,
		zoomControl: false,
		contextmenu: true,
		contextmenuWidth: 160,
		contextmenuItems: [{
		text: 'Chia sẻ địa điểm',
		icon: 'images/share.png',
		callback: shareLocation
		}
		, '-', {
		text: 'Trung tâm bản đồ',
		icon: 'images/center.png',
		callback: centerMap
		}, {
		text: 'Phóng to',
		icon: 'images/zoom-in.png',
		callback: zoomIn
		}, {
		text: 'Thu nhỏ',
		icon: 'images/zoom-out.png',
		callback: zoomOut
		}]
});


map.addControl(L.control.zoom({position: 'topright'}));		
var miniMap = new L.Control.MiniMap(mapQuest2, {toggleDisplay: true}).addTo(map);					

L.control.locate({
	drawCircle: false,
	follow: true,
	stopFollowingOnDrag: true
}).addTo(map);
L.control.layers(baseMaps).addTo(map);
map.addControl(new L.Control.Scale());

//	Handle context menu
function showCoordinatesA (e) {
	$("#route-function").show("fast");
	$("#locationA").val(e.latlng.lat.toFixed(6) + ", " + e.latlng.lng.toFixed(6));
	L.marker(e.latlng,{
          contextmenu: true,
          contextmenuItems: [{
              text: 'Địa điểm đánh dấu',
              index: 0
          }, {
              separator: true,
              index: 1
          }]
      }).addTo(map);
}

function showCoordinatesB (e) {
	$("#locationB").val(e.latlng.lat.toFixed(6) + ", " + e.latlng.lng.toFixed(6));
	L.marker(e.latlng).addTo(map);
}

function shareLocation (e) {
	$("#share-function").show("fast");
	if(markerShare == null || markerShare.length == 0){
		markerShare = L.marker(e.latlng,{
			contextmenu: true,
			contextmenuItems: [{
			  text: 'Vị trí bạn muốn chia sẻ',
			  index: 0
			}, {
			  separator: true,
			  index: 1
			}],
			draggable:true}).addTo(map);
	}else{
		markerShare.setLatLng(e.latlng);
	}
}

function centerMap (e) {
	map.panTo(e.latlng);
}

function zoomIn (e) {
	map.zoomIn();
}

function zoomOut (e) {
	map.zoomOut();
}
//	end handle context menu

function onLocationFound(e){
	L.marker(e.latlng,{
			contextmenu: true,
			contextmenuItems: [{
			  text: 'Vị trí hiện tại của bạn',
			  index: 0
			}, {
			  separator: true,
			  index: 1
			}],
			icon: geolocationIcon}).addTo(map);
	map.panTo(e.latlng);
	showLiveTrafficInfo();
}

function onLocationError(e){
	showLiveTrafficInfo();
}

map.on('locationfound', onLocationFound);
map.on('locationerror',onLocationError);
map.locate({setView: true, maxZoom: 16});
setInterval(function(){showLiveTrafficInfo()},1000*60*10);
/*end initial map*/

//		request delay 		//
var	counter;
function requestChangeView(){
	clearInterval(counter);
	var	count = 2;
	counter = setInterval(function(){
		count -= 1;
		if(count <= 0){
			clearInterval(counter);
			if(flagPast == 0) showLiveTrafficInfo();
			else showPastTrafficInfo();
			return;
		}
	},1000);
}
map.on('movestart', requestChangeView);
map.on('zoomend', function(){
	if(map.getZoom() > 16 && boundDistrictLayer != null){
		map.removeLayer(boundDistrictLayer);
		boundDistrictLayer = null;
	}
});

L.Marker.include(L.Mixin.ContextMenu);


//	handle map function
function backLiveMode(){
	if (flagPast == 1)	{
		flagPast = 0;		
		showLiveTrafficInfo();
		$('#live').prop('checked',true);
		$("div.cards-traffic-control").hide("fast");
	}
}

function clearLayer(nameLayer){
	if((map.hasLayer(nameLayer) == true) && (nameLayer != null)){
		map.removeLayer(nameLayer);
		nameLayer = null;
	}
}

//		set style for polyline
function weight_polyline(){
	switch (map.getZoom()){
		case 18: 	return	6; break;
		case 17: 	return	5; break;
		case 16: 	return	4; break;
		case 15: 	return	4; break;
		case 14:    return  3; break;
		default: 	return  2; 
	}
}

function d2h(d) {
	var hex = '0123456789ABCDEF';
	var r = '';
	d = Math.floor(d);
	while (d != 0) {
		r = hex[d % 16] + r;
		d = Math.floor(d / 16);
	}
	while (r.length < 2) r = '0' + r;
	return r;
}

function gradient(color) {
	// First arc (0, PI) in HSV colorspace
	function f2h(d) {
		return d2h(256 * d); 
	}
	if (color < 0)
		return "#FF0000";
	else if (color < 1.0/3)
		return "#FF" + f2h(3 * color) + "00";
	else if (color < 2.0/3)
		return "#" + f2h(2 - 3 * color) + "FF00";
	else if (color < 1)
		return "#00FF" + f2h(3 * color - 2);
	else
		return "#00FFFF";
};

function style(feature){
	return {
		opacity : 0.7,
		weight : weight_polyline(),
		color : gradient(feature.properties.v/60)
	};
}

//			end set style for polyline
function highlightFeature(e){
	var layer = e.target;
	layer.setStyle({
		weight : 7,
		opacity : 1
	});

	if(!L.Browser.ie && !L.Browser.opera){
		layer.bringToFront();
	}
	var popupPosition = L.popup().setLatLng(e.latlng).setContent(layer.feature.properties.v + " km/h").openOn(map);
	setTimeout(function(){map.closePopup(popupPosition);},2500);
}

function resetHighLight(e){
	trafficLayer.resetStyle(e.target);
}

function onEachFeature(feature, layer){
	layer.on({
		mouseover: highlightFeature,
		mouseout: resetHighLight,
	});
}

function popupMarker(e){
	var layer = e.target;
	var popupPosition = L.popup().setLatLng(e.latlng).setContent(layer.feature.properties.v + " km/h").openOn(map);
	setTimeout(function(){map.closePopup(popupPosition);},3000);
}

function onEachFeatureWarning(feature, layer){
	layer.on({
		click: popupMarker
	});
}

function showLiveTrafficInfo(){
	map.off('movestart',  requestChangeView);
	var latlngTL = map.getBounds().getNorthWest(),
		latlngTR = map.getBounds().getNorthEast(),
		latlngBL = map.getBounds().getSouthWest(),
		latlngBR = map.getBounds().getSouthEast();

	var geotraffic = {};
	geotraffic['type'] = "FeatureCollection";
	geotraffic['features'] = [];
	var url = 'http://traffic.hcmut.edu.vn/hcm/rest/rectangleSpeed?latTL=' + latlngTL.lat + '&lonTL=' + latlngTL.lng + '&latTR=' + latlngTR.lat + '&lonTR=' + latlngTR.lng + '&latBL=' + latlngBL.lat + '&lonBL=' + latlngBL.lng + '&latBR=' + latlngBR.lat + '&lonBR=' + latlngBR.lng + '&zoom=' + map.getZoom();

	if((map.getZoom() >= 17) && (flagWarning == 1)){
		var geowarning = {};
		geowarning['type'] = "FeatureCollection";
		geowarning['features'] = [];
	}

	$.ajax({
			url: url,
			type: 'GET',
			dataType: "json",
			timeout: 10000,

			success: function (data) {				
				if(data == null || data.length == 0){
					//alert("Lỗi tải dữ liệu giao thông từ server. Hãy thử lại");
					clearLayer(trafficLayer);
					clearLayer(warningLayer);				
				}
				else {
					var length = data.length;
					for(var i=0; i<length; i++){
						var segArray = data[i].v.split(',');
						segArray[0] = parseFloat(segArray[0]);
						segArray[1] = parseFloat(segArray[1]);
						segArray[2] = parseFloat(segArray[2]);
						segArray[3] = parseFloat(segArray[3]);
						segArray[4] = parseFloat(segArray[4]);
						var feature = {};
						feature['type'] = "Feature";
						feature['properties'] = {'v' : segArray[4]};
						var geometry = {};
						geometry['type'] = "LineString";
						geometry['coordinates'] = [[segArray[1],segArray[0]],[segArray[3],segArray[2]]];
						feature['geometry'] = geometry;
						geotraffic['features'].push(feature);
						if((map.getZoom() >= 17) && (flagWarning == 1) && (segArray[4] <= 10)){
							var featureP = {};
							featureP['type'] = "Feature";
							featureP['properties'] = {'v' : segArray[4]};
							var geometryP = {};
							geometryP['type'] = "Point";
							geometryP['coordinates'] = [(segArray[1]+segArray[3])/2,(segArray[0]+segArray[2])/2];
							featureP['geometry'] = geometryP;
							geowarning['features'].push(featureP);
						}
					}
					clearLayer(trafficLayer);
					clearLayer(warningLayer);
					trafficLayer = L.geoJson(geotraffic,{
						style : style,
						onEachFeature: onEachFeature
					}).addTo(map);
					if((flagWarning == 1) && (map.getZoom() >= 17)){
						warningLayer = L.geoJson(geowarning,{
							pointToLayer: function(feature, latlng){
								return L.userMarker(latlng,{pulsing:true});
							},
							onEachFeature: onEachFeatureWarning
						}).addTo(map);	
					}
				}
			},

			error: function(jqXHR){
				alert(jQuery.parseJSON(jqXHR.responseText));
				clearLayer(trafficLayer);
				clearLayer(warningLayer);				
			}
		});
	map.on('movestart',  requestChangeView);
}

function showPastTrafficInfo(){
	map.off('movestart',  requestChangeView);
	var latS = map.getBounds().getSouth(),
		lngS = map.getBounds().getWest(),
		latE = map.getBounds().getNorth(),
		lngE = map.getBounds().getEast();
	var geotraffic = {};
	geotraffic['type'] = "FeatureCollection";
	geotraffic['features'] = [];

	var url = 'http://traffic.hcmut.edu.vn/hcm/rest/trafficTime?latS='+latS+'&lonS='+lngS+'&latE='+latE+'&lonE='+lngE+'&date='+daytimePast[2]+'-'+daytimePast[1]+'-'+daytimePast[0]+'&hour='+daytimePast[3]+'&min='+daytimePast[4] + "&zoom" + map.getZoom();

	$.ajax({
			url: url,
			type: 'GET',
			dataType: "json",
			timeout: 10000,

			success: function (data) {				
				if(data == null || data.length == 0){
					//alert("Lỗi tải dữ liệu giao thông từ server. Hãy thử lại");
					clearLayer(trafficLayer);				
				}
				else {
					var length = data.length;
					for(var i=0; i<length; i++){
						var segArray = (data[i].v != null) ? data[i].v.split(',') : data[i].val.split(',');
						segArray[0] = parseFloat(segArray[0]);
						segArray[1] = parseFloat(segArray[1]);
						segArray[2] = parseFloat(segArray[2]);
						segArray[3] = parseFloat(segArray[3]);
						segArray[4] = parseFloat(segArray[4]);
						var feature = {};
						feature['type'] = "Feature";
						feature['properties'] = {'v' : segArray[4]};
						var geometry = {};
						geometry['type'] = "LineString";
						geometry['coordinates'] = [[segArray[1],segArray[0]],[segArray[3],segArray[2]]];
						feature['geometry'] = geometry;
						geotraffic['features'].push(feature);
					}
					clearLayer(trafficLayer);
					trafficLayer = L.geoJson(geotraffic,{
						style : style,
						onEachFeature: onEachFeature
					}).addTo(map);					
				}
			},

			error: function(jqXHR){
				alert(jQuery.parseJSON(jqXHR.responseText));
				clearLayer(trafficLayer);				
			}
		});
	map.on('movestart',  requestChangeView);
}


function zoomInCenterLocation(latlng,type,desc){
	map.setView(latlng, 17);
	if(markerLocation != null){
		markerLocation.setLatLng(latlng).bindPopup(desc).openPopup();
	}else{
		markerLocation = L.marker(latlng,{
			contextmenu: true,
			contextmenuItems: [{
			  text: 'Vị trí địa điểm',
			  index: 0
			}, {
			  separator: true,
			  index: 1
			}]});
		markerLocation.addTo(map);
		markerLocation.bindPopup(desc).openPopup();
	}
	switch(type){
		case "1": 			markerLocation.setIcon(coffee); break;
		case "2": 			markerLocation.setIcon(gas_station); break;
		case "3": 			markerLocation.setIcon(store); break;
		case "4": 			markerLocation.setIcon(repair_car); break;
		case "5": 			markerLocation.setIcon(parking_lot); break;
		case "6": 			markerLocation.setIcon(hospital); break;
	}
}

function zoomToProblem(latlng){
	map.setView(latlng, 16);
}

function showProblem(type){
	if(flagPast == 0){
		var geoproblem = [];
		$.ajax({
			url: 'http://traffic.hcmut.edu.vn/hcm/rest/policeWarning',
			type: 'GET',
			dataType: 'json',
			timeout: 5000,

			success: function(data){
				if(data == null){
					alert("Hiện tại không có tình huống giao thông nào được ghi nhận");
				}
				else {
					var length = data.dataModel.length;
					var countProblem = 0;
					var storage = [{"type":"jam", "location":[]},
						{"type":"construction", "location":[]},
						{"type":"accident", "location":[]},
						{"type":"flood", "location":[]},
						{"type":"police", "location":[]},
						{"type":"broken_light", "location":[]}
					];
					for(var i=0; i<length; i++){
						var problemPoint;
						switch (data.dataModel[i].type){
							case "jam": {
								problemPoint = L.marker([parseFloat(data.dataModel[i].latitude),parseFloat(data.dataModel[i].longitude)],{icon: warning});
								storage[0].location.push([data.dataModel[i].latitude,data.dataModel[i].longitude]);
							}; break;
							case "construction": {
								problemPoint = L.marker([parseFloat(data.dataModel[i].latitude),parseFloat(data.dataModel[i].longitude)],{icon: construction});
								storage[1].location.push([data.dataModel[i].latitude,data.dataModel[i].longitude]);
							}; break;
							case "accident": {
								problemPoint = L.marker([parseFloat(data.dataModel[i].latitude),parseFloat(data.dataModel[i].longitude)],{icon: accident});
								storage[2].location.push([data.dataModel[i].latitude,data.dataModel[i].longitude]);
							}; break;
							case "flood": {
								problemPoint = L.marker([parseFloat(data.dataModel[i].latitude),parseFloat(data.dataModel[i].longitude)],{icon: flood});
								storage[3].location.push([data.dataModel[i].latitude,data.dataModel[i].longitude]);
							}; break;
							case "police": {
								problemPoint = L.marker([parseFloat(data.dataModel[i].latitude),parseFloat(data.dataModel[i].longitude)],{icon: police});
								storage[4].location.push([data.dataModel[i].latitude,data.dataModel[i].longitude]);
							}; break;
							case "broken_light": {
								problemPoint = L.marker([parseFloat(data.dataModel[i].latitude),parseFloat(data.dataModel[i].longitude)],{icon: broken_light});
								storage[5].location.push([data.dataModel[i].latitude,data.dataModel[i].longitude]);
							}; break;
						}
						if(problemPoint != undefined){
							problemPoint.bindPopup("Thông tin được ghi nhận lúc <br>" + data.dataModel[i].timePost);
							geoproblem.push(problemPoint);
						}							
					}

					clearLayer(problemMarkerLayer);
					problemMarkerLayer = L.layerGroup(geoproblem).addTo(map);
					
					var html = "";
					html = '<br><div id="information-box">'
							+	'<table id="JamWrapper"></table>'
							+	'<table id="ConstructionWrapper"></table>'
							+	'<table id="AccidentWrapper"></table>'
							+	'<table id="FloodWrapper"></table>'
							+	'<table id="PoliceWrapper"></table>'
							+	'<table id="BrokenLinghtWrapper"></table>'
						+	'</div>';
					document.getElementById('output-box').innerHTML = html;	
					for(var i=0; i<storage.length; i++){
						switch(storage[i].type){
							case "jam":{
								appendToWeb(storage[i].location, "images/warning32.png", "JamWrapper", "đang xảy ra kẹt xe");
							}; break;
							case "construction":{
								appendToWeb(storage[i].location, "images/construction32.png", "ConstructionWrapper", "công trường đang có rào chắn thi công");
							}; break;
							case "accident":{
								appendToWeb(storage[i].location,  "images/accident32.png", "AccidentWrapper", "vừa xảy ra tai nạn giao thông");
							}; break;
							case "flood":{
								appendToWeb(storage[i].location,  "images/flood32.png", "FloodWrapper", "hiện tại đang ngập nước");
							}; break;
							case "police":{
								appendToWeb(storage[i].location,  "images/police32.png", "PoliceWrapper", "cảnh sát giao thông làm nhiệm vụ");
							}; break;
							case "broken_light":{
								appendToWeb(storage[i].location,  "images/broken_light32.png", "BrokenLinghtWrapper", "bị hỏng đèn tín hiệu");
							}; break;
						}
					}

				}
			}
		});
		
	}
}

function appendToWeb(arr, img, dom, type){
	if(arr.length != 0) {
		$('#' + dom).append('<tr><td class="number-proplem">' + arr.length + '</td><td class="note-text" style="color: blue;"> địa điểm ' + type + '</td></tr>');
		for(var j=0; j<arr.length; j++){
			var worker = new Worker('js/RequestNameLocation.js');
			worker.postMessage(arr[j]);
			worker.onmessage = function(e){
			
				var respond = jQuery.parseJSON(e.data);				
				var appendContent = "";
				appendContent += '<tr class="item-problem" onclick="zoomToProblem(['+ respond.lat + ', ' + respond.lon + '])">';
				appendContent += '<td class="image-problem"><img src="' + img + '" alt="" /></td>';
				appendContent += '<td class="notes-problem"><div class="note-text">' + respond.display_name + '</div></td></tr>';
				$('#' + dom).append(appendContent);
			};							
		}
	}
}

function showLocation(latlng, type, radius){
	var url = 'http://traffic.hcmut.edu.vn/Placevn/rest/getplace?lat=' + latlng[0] + '&lon=' + latlng[1] + '&type=' + type + '&r=' + radius;
	var geolocation = [];	
	$.ajax({
		url: url,
		type: 'GET',
		dataType: 'json',
		timeout: 5000,

		success: function(data){
			if(data == null) alert("Chưa có dữ liệu địa điểm trong vùng này. Bạn có thể chia sẻ địa điểm thông qua chức năng chia sẻ");
			else {
				var length = data.geoPoint.length;
				var counterLocation = 0;
				var storage = [];
				for(var i=0; i<length; i++){
					var locationPoint;
					switch (data.geoPoint[i].type){
						case "1": locationPoint = L.marker([parseFloat(data.geoPoint[i].latitude),parseFloat(data.geoPoint[i].longitude)],{icon: coffee}); break;
						case "2": locationPoint = L.marker([parseFloat(data.geoPoint[i].latitude),parseFloat(data.geoPoint[i].longitude)],{icon: gas_station}); break;
						case "3": locationPoint = L.marker([parseFloat(data.geoPoint[i].latitude),parseFloat(data.geoPoint[i].longitude)],{icon: store}); break;
						case "4": locationPoint = L.marker([parseFloat(data.geoPoint[i].latitude),parseFloat(data.geoPoint[i].longitude)],{icon: repair_car}); break;
						case "5": locationPoint = L.marker([parseFloat(data.geoPoint[i].latitude),parseFloat(data.geoPoint[i].longitude)],{icon: parking_lot}); break;
						case "6": locationPoint = L.marker([parseFloat(data.geoPoint[i].latitude),parseFloat(data.geoPoint[i].longitude)],{icon: hospital}); break;
						default: locationPoint = 0;
					}
					if(locationPoint != 0){
						var desc_location = data.geoPoint[i].name + "<br>Địa chỉ: " + data.geoPoint[i].addr + ", P." + data.geoPoint[i].ward + ", Q." + data.geoPoint[i].disc + "<br>Mô tả: " + data.geoPoint[i].desrc + "<br>Số ĐT liên hệ: 0" + data.geoPoint[i].phone;
						locationPoint.bindPopup(desc_location);
						geolocation.push(locationPoint);
						counterLocation++;
						storage.push([data.geoPoint[i].latitude, data.geoPoint[i].longitude, data.geoPoint[i].type, desc_location]);
					}						
				}
				clearLayer(locationMarkerLayer);
				locationMarkerLayer = L.layerGroup(geolocation).addTo(map);
				var html = "";
				html += '<div id="information-box-location"><h4>Tìm được ' + counterLocation + ' địa điểm theo yêu cầu. </h4>';
				html += '<table class="table-output">'
				for(var i=0; i<counterLocation; i++){
					var srcImage = "";
					switch (storage[i][2]){
						case "1": srcImage = "images/coffee32.png"; break;
						case "2": srcImage = "images/gas_station32.png"; break;
						case "3": srcImage = "images/store32.png"; break;
						case "4": srcImage = "images/repair_car32.png"; break;
						case "5": srcImage = "images/parking_lot32.png"; break;
						case "6": srcImage = "images/hospital32.png"; break;
					}
					html += '<tr class="item-problem" onclick="zoomInCenterLocation(['+ storage[i][0] + ', ' + storage[i][1] + '], \'' + storage[i][2] + '\', \'' + storage[i][3] + '\')">';
					html += '<td class="image-problem"><img src="' + srcImage + '" alt="" /></td>';
					html += '<td class="notes-problem">';
					html += '<div class="note-text">' + storage[i][3] + '</div>';
					html += '</td></tr>';
				}
				html += '</table></div>';
				document.getElementById('output-box-location').innerHTML = html;
			}
		},
	});
}


function BoundDistrict(IDdistrict){
	var polygonDist;
	switch(IDdistrict){
		case 1: polygonDist = dist1; break;
		case 2: polygonDist = dist2; break;
		case 3: polygonDist = dist3; break;
		case 4: polygonDist = dist4; break;
		case 5: polygonDist = dist5; break;
		case 6: polygonDist = dist6; break;
		case 7: polygonDist = dist7; break;
		case 8: polygonDist = dist8; break;
		case 9: polygonDist = dist9; break;
		case 10: polygonDist = dist10; break;
		case 11: polygonDist = dist11; break;
		case 12: polygonDist = dist12; break;
		case 13: polygonDist = distBT; break;
		case 14: polygonDist = distBTh; break;
		case 15: polygonDist = distGV; break;
		case 16: polygonDist = distPN; break;
		case 17: polygonDist = distTB; break;
		case 18: polygonDist = distTP; break;
		case 19: polygonDist = distTD; break;
		default: polygonDist = [];
	}
	clearLayer(boundDistrictLayer);
	boundDistrictLayer = L.polygon(polygonDist, {color: "#F00", fillColor: "#00F", opacity: 1, fillOpacity: 0.05, weight: 3}).addTo(map);						
}

function shareInfo(latlng, type){
	var url = 'http://traffic.hcmut.edu.vn/hcm/police?latPos=' + latlng[0] + '&longPos=' + latlng[1] + '&type=' + type;
	$.ajax({
		url: url,
		success:function(result){
      		
    	}
    });
}

function shareLocation(latlng, type, name, street, ward, disc){	
	var url = 'http://traffic.hcmut.edu.vn/Placevn/rest/add?lat=' + latlng[0] + '&lon=' + latlng[1] + '&type=' + type + '&name=' + name + '&street=' + street + '&ward=' + ward + '&disc=' + disc;
	$.ajax({
		url: url,
		type: 'GET',
		dataType: 'json',
		timeout: 5000,

		success:function(data){
      		if(data.success == "1" || data.success == "0"){
      			$('#input-error').text("");
				$('#success-share-location').text("Bạn đã chia sẻ thành công");      			
      		}else{
      			$('#input-error').text("Lỗi chia sẻ địa điểm. Vui lòng thủ lại");
      		}

    	},
    	error: function(jqXHR){
			$('#input-error').text("Lỗi ghi nhận dữ liệu phía server. Vui lòng thử lại");				
		}
    });
}